package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ：seanyang
 * @date ：Created in 2019/7/1
 * @description ：授权实现类
 * @version: 1.0
 */
@Component
@Slf4j
public class SecurityUserDetailService  implements UserDetailsService {

	@Reference
	private UserService userService;

	/**
	 * 1.通过UserService读取数据库信息
	 * 2.读取角色及权限关键词，封装权限列表
	 * 3.封装UserDetails
	 * 4.返回UserDetails
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 读取用户信息
		User user = userService.findByUsername(username);
		if(user == null){
			log.debug("auth fail....");
			return null;
		}
		// 读取角色及权限关键词，封装权限列表
		List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
		Set<Role> roleSet = user.getRoles();
		for (Role role:roleSet){
			// 把角色关键词封装到列表，ROLE_
			grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
			Set<Permission> permissionSet = role.getPermissions();
			for (Permission permission :permissionSet){
				// 把权限关键词封装到列表
				grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
			}
		}
		// 封装UserDetail, User
		UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthorityList);
		return userDetails;
	}
}
